#include "key.h"

#define KEY_PORT			P1
#define ROW_PIN_MASK	0x0F
#define COL_PIN_MASK	0xF0
#define ROW_PIN_VAL 	(KEY_PORT&ROW_PIN_MASK)
#define COL_PIN_VAL		(KEY_PORT&COL_PIN_MASK)

typedef enum{
	KEY_SCAN_STA_ROW = 0x00,
	KEY_SCAN_STA_COL
}KEY_SCAN_STA;

void key_set_scan_sta(KEY_SCAN_STA sta)
{
	if(sta==KEY_SCAN_STA_ROW)
	{
		P1MDOUT = ~ROW_PIN_MASK;
		KEY_PORT = ROW_PIN_MASK;
	}else if(sta==KEY_SCAN_STA_COL)
	{
		P1MDOUT = ~COL_PIN_MASK;
		KEY_PORT = ROW_PIN_MASK;
	}
}


KEY key_scan(void){
	static u8 is_key_down = 0;
	KEY key = KEY_NONE;
	key_set_scan_sta(KEY_SCAN_STA_COL);
	if(COL_PIN_VAL!=COL_PIN_MASK)
	{
		if(!is_key_down)
		{
			sys_delay_about_ms(10);//??
			if(COL_PIN_VAL!=COL_PIN_MASK)
			{
				switch(COL_PIN_VAL)
				{
					case 0xE0:
						key = 1;//???1?????
						break;
					case 0xD0:
						key=2;
						break;
					case 0xB0: 
						key = 3;//???3?????
						break;
					case 0x70: 
						key = 4;//???4?????
						break;
				}
				
				key_set_scan_sta(KEY_SCAN_STA_ROW);
				sys_delay_about_us(1);//????????
				switch(ROW_PIN_VAL)
				{
					case 0x0E: 
						key += 0;//???1?????
						break;
					case 0x0D:  
						key += 4;//???2?????
						break;
					case 0x0B: 
						key += 8;//???3?????
						break;
					case 0x07: 
						key += 12;//???4?????
						break;
				}		
				is_key_down = 1;
			}
		}
	}else
	{
		is_key_down = 0;
	}
	return key;
	
}

